package com.xyz.business.action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.xyz.base.action.PageAction;
import com.xyz.business.bean.Enterprise;
import com.xyz.business.bean.Report;
import com.xyz.business.service.EnterpriseService;
import com.xyz.business.service.ReportService;
import com.xyz.business.service.UserService;
import com.xyz.business.service.impl.ReportHelper;
import com.xyz.business.service.impl.UserHelper;
import com.xyz.constant.XYZConstant;
import com.xyz.init.infos.UserInfosInit;
import com.xyz.util.date.DateStyle;
import com.xyz.util.date.DateUtil;

/**
 * 
 * @author xyzjh
 * 
 */
public class ReportAction extends PageAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5469108171976815655L;
	/**
	 * 日志类
	 */
	private static Logger log = Logger.getLogger(ReportAction.class);
	private String fileName;

	private InputStream downloadStream;

	private Report report;

	private Enterprise enterprise;

	private ReportService reportService;

	private UserService userService;
	private EnterpriseService enterpriseService;
	private Integer flag = 0;
	/**
	 * 统计开始时间
	 */
	private Date beginTime;
	/**
	 * 统计结束时间
	 */
	private Date endTime;

	public String page() {
		baseMethod(getRequest(), userService);
		getRequest().setAttribute("showresultflag", null);
		return SUCCESS;
	}

	public String frontcover() {
		String rid = getRequest().getParameter("rptId");
		try {
			report = reportService.queryReportByRptId(rid);
			String eid = report.getEid();
			enterprise = enterpriseService.queryEnterpriseByEid(eid);
		} catch (SQLException e) {
			log.error(" cathc one exception when query:" + e);
		}
		return SUCCESS;
	}

	public String division() {
		String rid = getRequest().getParameter("rptId");
		try {
			report = reportService.queryReportByRptId(rid);
			String eid = report.getEid();
			enterprise = enterpriseService.queryEnterpriseByEid(eid);
		} catch (SQLException e) {
			log.error(" cathc one exception when query:" + e);
		}
		return SUCCESS;
	}

	public String query() {
		baseMethod(getRequest(), userService);
		List reportList = new ArrayList(32);
		try {
			setRowCount(reportService.queryReportCount(report, enterprise));
			baseDeal();
			// setPageSize(reportService.queryReportCount(report, enterprise));
			reportList = reportService.query(report, enterprise,
					(getPageNow() - 1) * getPageSize(), getPageSize());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			log.error(" cathc one exception when query:" + e);
		}

		getRequest().setAttribute("reportList", reportList);
		return SUCCESS;
	}

	public String queryDetail() {
		List reportList = new ArrayList(32);
		baseMethod(getRequest(), userService);
		try {
			// setPageSize(reportService.queryReportCount(report, enterprise));
			reportList = reportService.query(report, enterprise,
					(getPageNow() - 1) * getPageSize(), getPageSize());
			// 根据报告号，或者企业号查询企业信息
			// 目前只写一个页面，查询报告的所有信息
			// 因为报告号是唯一的
			if (reportList != null) {
				Map<String, Object> detail = (Map<String, Object>) reportList
						.get(XYZConstant.NUM_0);
				dealDeail(detail);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			log.error(" cathc one exception when query:" + e);
		}
		return SUCCESS;
	}

	private void dealDeail(Map<String, Object> detail) {
		enterprise = new Enterprise();
		report = new Report();

	}

	/**
	 * 创建报告
	 * 
	 * @return
	 */
	public String addReport() {
		log.info("insert begin...");
		try {
			if (null != flag) {
				// 新增
				if (XYZConstant.ADD_FLAG == flag) {
					reportService.insert(report, enterprise);
				}
				// 修改
				else if (XYZConstant.MODIFY_FLAG == flag) {
					reportService.update(report, enterprise);
				}
			}

		} catch (SQLException e) {
			log.error("catch one sqlexception:" + e);
		}
		baseMethod(getRequest(), userService);
		return SUCCESS;
	}

	/**
	 * 在报告列表页面点击修改按钮、查询报告对应的信息
	 * 
	 * @return
	 */
	public String edit() {
		String rid = getRequest().getParameter("rptId");
		try {
			report = reportService.queryReportByRptId(rid);
			String eid = report.getEid();
			enterprise = enterpriseService.queryEnterpriseByEid(eid);
		} catch (SQLException e) {
			log.error(" cathc one exception when query:" + e);
		}

		baseMethod(getRequest(), userService);
		return SUCCESS;
	}

	/**
	 * 删除，后台实际隐藏，将报告表中的ishide字段值该为1
	 * 
	 * @return
	 */
	public String delete() {

		String rptid = getRequest().getParameter("rptId");
		try {
			reportService.hide(rptid);
		} catch (SQLException e) {
			log.error("catch one sqlexception:" + e);
		}
		baseMethod(getRequest(), userService);
		return SUCCESS;

	}

	public void baseMethod(HttpServletRequest request, UserService userService) {
		// 获取公司性质等下拉列表
		ReportHelper.baseMethod(request);
		// 获取各种用户下拉列表
		UserHelper.dealUser(request, userService);
	}

	/**
	 * 导出采集数据
	 * 
	 * @return
	 */
	public String exportCollect() {

		String rid = getRequest().getParameter("rptId");
		try {
			report = reportService.queryReportByRptId(rid);
			String eid = report.getEid();
			enterprise = enterpriseService.queryEnterpriseByEid(eid);
		} catch (SQLException e) {
			log.error(" cathc one exception when query:" + e);
		}

		String temfilename = ReportHelper.getCollectFileName(report
				.getReportno());
		setFileName(temfilename);

		List<String> staticTitle = ReportHelper.getStatictitle();
		XSSFWorkbook workbook = new XSSFWorkbook();
		XSSFCellStyle style = workbook.createCellStyle();
		style.setAlignment(XSSFCellStyle.VERTICAL_CENTER);
		style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
		XSSFSheet sheet = workbook.createSheet("sheet1");
		XSSFCell cell = null;
		XSSFRow row = null;
		// for (int index = 0,size=staticTitle.size(); index < size; index++) {
		// 第一行 编号
		row = sheet.createRow(0);
		cell = row.createCell(0);
		cell.setCellValue(staticTitle.get(0));
		cell = row.createCell(1);
		cell.setCellValue("1");// 编号暂定为1
		// 第二行 报告年度
		row = sheet.createRow(1);
		cell = row.createCell(0);
		cell.setCellValue(staticTitle.get(1));
		cell = row.createCell(1);
		cell.setCellValue(report.getReportyear());
		// 第三行 报告字号
		row = sheet.createRow(2);
		cell = row.createCell(0);
		cell.setCellValue(staticTitle.get(2));
		cell = row.createCell(1);
		cell.setCellValue(report.getReporttypename());

		// 第四行 报告单号
		row = sheet.createRow(3);
		cell = row.createCell(0);
		cell.setCellValue(staticTitle.get(3));
		cell = row.createCell(1);
		cell.setCellValue(report.getReportno());

		// 第五行 企业名称
		row = sheet.createRow(4);
		cell = row.createCell(0);
		cell.setCellValue(staticTitle.get(4));
		cell = row.createCell(1);
		cell.setCellValue(enterprise.getCompanyname());

		// 第二行 地址
		row = sheet.createRow(5);
		cell = row.createCell(0);
		cell.setCellValue(staticTitle.get(5));
		cell = row.createCell(1);
		cell.setCellValue(enterprise.getBusineaddre());

		// 第二行 开业时间
		row = sheet.createRow(6);
		cell = row.createCell(0);
		cell.setCellValue(staticTitle.get(6));
		cell = row.createCell(1);
		Date openDate = enterprise.getOpendate();
		cell.setCellValue(DateUtil.DateToString(openDate, DateStyle.YYYY_MM_DD));

		// 第二行 经营范围
		row = sheet.createRow(7);
		cell = row.createCell(0);
		cell.setCellValue(staticTitle.get(7));
		cell = row.createCell(1);
		cell.setCellValue(enterprise.getScopebusiness());

		// 第二行 营业执照号
		row = sheet.createRow(8);
		cell = row.createCell(0);
		cell.setCellValue(staticTitle.get(8));
		cell = row.createCell(1);
		cell.setCellValue(enterprise.getBusinesslicense());

		// 第二行 企业性质
		row = sheet.createRow(9);
		cell = row.createCell(0);
		cell.setCellValue(staticTitle.get(9));
		cell = row.createCell(1);
		String nature = enterprise.getEnterprisenature();
		cell.setCellValue(ReportHelper.getNatureMap().get(nature));

		// 第二行 法人名称
		row = sheet.createRow(10);
		cell = row.createCell(0);
		cell.setCellValue(staticTitle.get(10));
		cell = row.createCell(1);
		cell.setCellValue(enterprise.getLowperson());

		// 第二行 注册资本(万元)
		row = sheet.createRow(11);
		cell = row.createCell(0);
		cell.setCellValue(staticTitle.get(11));
		cell = row.createCell(1);
		cell.setCellValue(enterprise.getRegisteredcapital());

		// 第二行 国税地税
		row = sheet.createRow(12);
		cell = row.createCell(0);
		cell.setCellValue(staticTitle.get(12));
		cell = row.createCell(1);
		cell.setCellValue(ReportHelper.getTaxTpeMap().get(
				enterprise.getTaxtype()));

		// 第二行 国税登记证号
		row = sheet.createRow(13);
		cell = row.createCell(0);
		cell.setCellValue(staticTitle.get(13));
		cell = row.createCell(1);
		cell.setCellValue(enterprise.getNationaltaxno());

		// 第二行 地税登记证号
		row = sheet.createRow(14);
		cell = row.createCell(0);
		cell.setCellValue(staticTitle.get(14));
		cell = row.createCell(1);
		cell.setCellValue(enterprise.getLocaltaxno());

		// }

		// for(int j=0;j<17;j++){
		// sheet.autoSizeColumn(j); //调整第j列宽度,自动的哦
		// }

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		try {
			outputStream.flush();
			workbook.write(outputStream);
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] byteArray = outputStream.toByteArray();
		downloadStream = new ByteArrayInputStream(byteArray, 0,
				byteArray.length);

		return SUCCESS;
	}

	/**
	 * 导出统计数据
	 * 
	 * @return
	 */
	public String exportStatistic() {
//		String temfilename = ReportHelper.getSataicFileName(beginTime, endTime);
		String dates = report.getReportyear();
		if (StringUtils.isBlank(report.getReportyear())) {
			dates = DateUtil.DateToString(new Date(), DateStyle.YYYY);
			report.setReportyear(dates);
		}
		String temfilename = new StringBuffer(32).append("Statistics_").append(dates).toString();
		setFileName(temfilename);
		try {
			List datalist = reportService.queryCollect(report, enterprise,
					beginTime, endTime);
			List<String> collectTitle = ReportHelper.getCollecttitle();
			XSSFWorkbook workbook = new XSSFWorkbook();
			XSSFCellStyle style = workbook.createCellStyle();
			style.setAlignment(XSSFCellStyle.VERTICAL_CENTER);
			style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
			XSSFSheet sheet = workbook.createSheet("sheet1");
			XSSFRow row = sheet.createRow(0);
			XSSFCell cell = null;
			/**
			 * 创建表头
			 */
			for (int index = 0, size = collectTitle.size(); index < size; index++) {
				cell = row.createCell(index);
				cell.setCellValue(collectTitle.get(index));
				cell.setCellStyle(style);
			}
			if (datalist != null) {
				for (int index = 0, size = datalist.size(); index < size; index++) {
					Map<String, Object> map = (Map<String, Object>) datalist
							.get(index);
					row = sheet.createRow(index + 1);
					cell = row.createCell(0);
					cell.setCellValue((String) (map.get("reportyear")));

					cell = row.createCell(1);
					cell.setCellValue((String) map.get("reporttypename"));

					cell = row.createCell(2);
					cell.setCellValue(String.valueOf(map.get("reportno")));

					cell = row.createCell(3);
					cell.setCellValue((String) map.get("companyname"));

					cell = row.createCell(4);
					cell.setCellValue(String.valueOf(map.get("treatyprice")));

					cell = row.createCell(5);
					String contactperson = UserInfosInit.getName((String) map
							.get("contactperson"));
					cell.setCellValue(contactperson);

					cell = row.createCell(6);
					String projectleader = UserInfosInit.getName((String) map
							.get("projectleader"));
					cell.setCellValue(projectleader);
					
					cell = row.createCell(7);
					String cpaone = UserInfosInit.getName((String) map
							.get("cpaone"));
					cell.setCellValue(cpaone);

					cell = row.createCell(8);
					String cpatwo = UserInfosInit.getName((String) map
							.get("cpatwo"));
					cell.setCellValue(cpatwo);
					
					
					cell = row.createCell(9);
					String helpmateone = UserInfosInit.getName((String) map
							.get("helpmateone"));
					cell.setCellValue(helpmateone);

					cell = row.createCell(10);
					String helpmatetwo = UserInfosInit.getName((String) map
							.get("helpmatetwo"));
					cell.setCellValue(helpmatetwo);

					cell = row.createCell(11);
					String helpmatethree = UserInfosInit.getName((String) map
							.get("helpmatethree"));
					cell.setCellValue(helpmatethree);

					cell = row.createCell(12);
					Date invoicedate = (Date) map.get("invoicedate");
					String invoicedateStr = DateUtil.DateToString(invoicedate,
							DateStyle.YYYY_MM_DD);
					cell.setCellValue(invoicedateStr);

					cell = row.createCell(13);
					cell.setCellValue(map.get("receiptsum")==null?0:(Integer) map.get("receiptsum"));

					cell = row.createCell(14);
					Date receiptdate = null == map.get("receiptdate") ? null
							: (Date) map.get("receiptdate");
					String receiptdateStr = DateUtil.DateToString(receiptdate,
							DateStyle.YYYY_MM_DD);
					cell.setCellValue(receiptdateStr);

					cell = row.createCell(15);
					Integer clearway = null == map.get("clearway") ? XYZConstant.NUM_0
							: (Integer) map.get("clearway");

					cell.setCellValue(ReportHelper.getClearWayMap().get(
							clearway));
				}
			}

			// for (int j = 0; j < 14; j++) {
			// sheet.autoSizeColumn(j); // 调整第j列宽度,自动的哦
			// }

			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			workbook.write(outputStream);
			outputStream.flush();
			byte[] byteArray = outputStream.toByteArray();
			downloadStream = new ByteArrayInputStream(byteArray, 0,
					byteArray.length);

			outputStream.close();

		} catch (SQLException e) {
			log.error("catch one SQLException:" + e);
		} catch (IOException e) {
			log.error("catch one IOException:" + e);
		}
		return SUCCESS;
	}

	public Report getReport() {
		return report;
	}

	public void setReport(Report report) {
		this.report = report;
	}

	public Enterprise getEnterprise() {
		return enterprise;
	}

	public void setEnterprise(Enterprise enterprise) {
		this.enterprise = enterprise;
	}

	public ReportService getReportService() {
		return reportService;
	}

	public void setReportService(ReportService reportService) {
		this.reportService = reportService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public EnterpriseService getEnterpriseService() {
		return enterpriseService;
	}

	public void setEnterpriseService(EnterpriseService enterpriseService) {
		this.enterpriseService = enterpriseService;
	}

	public Integer getFlag() {
		return flag;
	}

	public void setFlag(Integer flag) {
		this.flag = flag;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public InputStream getDownloadStream() {
		return downloadStream;
	}

	public void setDownloadStream(InputStream downloadStream) {
		this.downloadStream = downloadStream;
	}

	public Date getBeginTime() {
		return beginTime;
	}

	public void setBeginTime(Date beginTime) {
		this.beginTime = beginTime;
	}

	public Date getEndTime() {
		return endTime;
	}

	public void setEndTime(Date endTime) {
		this.endTime = endTime;
	}

}
